<?php
namespace App\Admin\Controllers\Reimburse;

use App\Admin\Actions\Reimburse\BatchPaid;
use App\Admin\Ajax\Reimburse\PaidAjax;
use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\AmazonCountry;
use App\Models\Basics\SysCountry;
use App\Models\Basics\Currency;
use App\Models\Reimburse\ReimburseApply;
use App\Models\Reimburse\ReimbursePaid;
use App\Util\RExcel;
use App\Util\User;
use Encore\Admin\Admin;
use Encore\Admin\Admin as SAdmin;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request as FRequest;
use Illuminate\Support\Facades\Request;
class PaidController extends AdminController{

    protected $title = '返款支付';

    protected function _style()
    {
        return <<<STYLE
.table > thead > tr > th, .column-操作 {
    white-space: nowrap;
}
.table-responsive {
    max-height: calc(80vh);
}
STYLE;
    }

    protected function grid()
    {
        SAdmin::style($this->_style());
        $grid = new Grid(new ReimbursePaid());
        $grid->model()->where('audit_status',2)->orderBy('id', 'DESC');
        $grid->model()->collection(function (Collection $collection){
            foreach($collection as $item) {
                $item->sku = [$item->apply->sku->psku_code ?? '',$item->apply->sku->psku_cn ?? '',$item->apply->skuClassify->title ?? ''];
            }
            return $collection;
        });
        $grid->column('created_at','创建时间');
        $grid->column('paid_status','付款状态')->using(ReimbursePaid::$_paidStatus);
        $grid->column('order_by','类型')->using(ReimbursePaid::$_orderBy);
        $grid->column('apply.order_no','订单号/费用描述');
        $grid->column('apply.country_id','国家')->display(function ($value){
            return SysCountry::getCountryById($value);
        });
        $grid->column('apply.seller_id','销售员')->display(function ($value){
            return User::getUsernameById($value);
        });
        $grid->column('apply.seller_sku','亚马逊SKU');
        $grid->column('sku','SKU')->display(function ($value){
            return $value ? '<span class="label" style="color: #000;font-weight: 500;font-size: 85%;padding: .2em 0 .3em;">'.implode('<br>',$value).'</span>' : '';
        });
        $grid->column('paid_method','支付方式')->using(ReimburseApply::$_paidMethod);
        $grid->column('paid_account_no','支付账号')->display(function ($value){
            return '<span style="font-size: 85%;padding: .2em 0 .3em;">'.$value.'</span>';
        });
        $grid->column('currency_code','币种')->display(function ($value){
            return Currency::getNameByCode($value);
        });
        $grid->column('paid_amount','支付金额(原币)');
        $grid->column('paid_date','付款时间');
        $grid->column('apply.remarks','备注')->style('min-width:50px;max-width:120px');
        Admin::script($this->_script());
        $grid->column('操作')->view('reimburse.paid.action');

        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->batchActions(function ($batch) {
            $batch->disableDelete();
            $batch->add(new BatchPaid());
        });
        $grid->disableExport();
        $grid->tools(function (Grid\Tools $tools){
            $tools->append(new Export('reimburse/paid-download'));
        });
        $grid->paginate(10);
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->like('paid_account_no', '支付账号');
                $filter->equal('paid_status','付款状态')->select(ReimbursePaid::$_paidStatus);
                $filter->where(function ($query) {
                    $query->whereHas('apply', function ($query) {
                        $query->whereIn('order_no', explode(',',"{$this->input}"));
                    });
                }, '订单号','orderNo')->placeholder('多订单查询用英文逗号隔开');
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('currency_code', '币种')->select(Currency::options());
                $filter->equal('apply.country_id','国家')->select(AmazonCountry::options());
                $filter->equal('apply.seller_id','销售')->select(User::getSellerOptions());

            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('paid_method','支付方式')->select(ReimburseApply::$_paidMethod);
                $filter->between('paid_date', '付款时间')->datetime();
            });
        });
        return $grid;
    }

    protected function _script()
    {
        return <<<EOT
$('.grid-check-row').on('click', function () {
    var id = $(this).data('id');
    $("#myModal").modal({
        remote : '/xqc/reimburse/paid-modal?action=paidFile&param=' + id
    });
});

$("#myModal").on("hidden.bs.modal", function() {
    $(this).removeData("bs.modal");
    $(this).find(".modal-content").children().remove();
});
EOT;
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new PaidAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }
    public function trace(FRequest $request){
        $action = $request->get('action');
        $param = $request->get('param');
        $file = $request->file('source_file');
        $trace = new PaidAjax();
        return $param ? call_user_func([$trace,$action],$file,$param) : call_user_func([$trace,$action],$file);
    }

    public function modal(){
        $action = request('action');
        $param = request('param');
        $modal = new PaidAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }

    public function paid(Content $content)
    {
        $ids = explode(',',Request::get('id'));
        $rps = ReimbursePaid::query()
            ->whereIn('id',$ids)
            ->where('audit_status',2)
            ->where('paid_status',1)
            ->get();
        return $content->header('返款支付')
            ->description('批量支付')
            ->body(view('reimburse.paid.index', compact('rps')));
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = ReimbursePaid::query()->where('audit_status',2)->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'paid_account_no'){
                $query->where(function ($query) use($_filter){
                    $query->where('paid_account_no', 'like', "%{$_filter}%");
                });
            }
            if($key == 'orderNo'){
                $query->whereHas('apply', function ($query)use($_filter){
                    $query->whereIn('order_no', explode(',',"{$_filter}"));
                });
            }
            if($key == 'apply'){
                $query->whereHas('apply', function ($query)use($_filter){
                    foreach ($_filter as $field => $filter){
                        $query->where($field, $filter);
                    }
                });
            }
            if($key == 'paid_date'){
                if(isset($_filter['start'])&&$_filter['start']){
                    $query->where('paid_date','>=',$_filter['start']);
                }
                if(isset($_filter['end'])&&$_filter['end']){
                    $query->where('paid_date','<=',$_filter['end']);
                }
            }
            if(in_array($key,['paid_status','currency_code','country_id','seller_id','paid_method'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        $head = ['提报时间','付款状态','提报单号','类型','订单号/费用描述','国家','销售员','亚马逊SKU',
            'SKU','SKU名称','品类','支付方式','支付账号','币种','支付金额(原币)','付款时间','备注'];
        RExcel::exportCsv('返款支付',function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = self::_getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    private static function _getDownloadData($res)
    {
        $country = [];
        $seller = [];
        foreach ($res as $model){
            $countryId = $model->apply->country_id ?? 0;
            if(!array_key_exists($countryId,$country)){
                $country[$countryId] = SysCountry::getCountryById($countryId);
            }
            $sellerId = $model->apply->seller_id ?? 0;
            if(!array_key_exists($sellerId,$seller)){
                $seller[$sellerId] = User::getUsernameById($sellerId);
            }
            $temp = [
                $model->created_at,
                ReimburseApply::$_paidStatus[$model->paid_status],
                $model->reimburse_no,
                ReimbursePaid::$_orderBy[$model->order_by],
                $model->apply->order_no ?? '',
                $country[$countryId],
                $seller[$sellerId],
                $model->apply->seller_sku ?: '',
                $model->apply->sku->psku_code ?? '',
                $model->apply->sku->psku_cn ?? '',
                $model->apply->skuClassify->title ?? '',
                ReimburseApply::$_paidMethod[$model->paid_method],
                $model->paid_account_no,
                $model->currency_code,
                $model->paid_amount,
                $model->paid_date,
                $model->apply->remarks ?? '',
            ];
            yield $temp;
        }
    }
}
